<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Lazy Img</title>
    <style media="screen">
      img {
        display: block;
        border-bottom: 1px solid red;
      }
    </style>
  </head>
  <body>
    <h1>Img Lazy Load</h1>
    <img class="lazy-load" src="images/qrcode.png" data-src="images/w3c.jpg" />
    <img class="lazy-load" src="images/qrcode.png" data-src="images/avatar.png" />
    <img class="lazy-load" src="images/qrcode.png" data-src="images/download.jpg" />
    <img class="lazy-load" src="images/qrcode.png" data-src="images/github.png" />
    <img class="lazy-load" src="images/qrcode.png" data-src="images/react.png" />
    <img class="lazy-load" src="images/qrcode.png" data-src="images/tower.png" />
    <img class="lazy-load" src="images/qrcode.png" data-src="images/untitled.png" />
    <img class="lazy-load" src="images/qrcode.png" data-src="images/zhihu.png" />
    <img class="lazy-load" src="images/qrcode.png" data-src="images/zhihu2.png" />
    <script type="text/javascript">
      function throttle(fn, limit) {
        var inThrottle = undefined
        return function(...args) {
          if (!inThrottle) {
            fn.apply(this, args)
            inThrottle = true
            var timeoutFn = () => inThrottle = false
            setTimeout(timeoutFn, limit)
          }
        }
      }
    </script>
    <script type="text/javascript">
      window.onload = () => {
        var images = document.getElementsByClassName('lazy-load')
        for (let j = 0; j < images.length; j++) {
          const topBoundary = images[j].offsetTop - window.scrollY
          const bottomBoundary = topBoundary + images[j].clientHeight
          if (topBoundary < window.innerHeight && bottomBoundary > 0) {
            images[j].src = images[j].getAttribute('data-src')
          }
        }
      }
      window.onscroll = () => {
        // body 滚动高度
        var bodyScrollHeight =  document.body.scrollTop
        // 视窗高度
        var windowHeight = window.innerHeight
        var imgs = document.getElementsByClassName('lazy-load')
        for (var i = 0; i < imgs.length; i++) {
          // 图片距离顶部高度
          var imgHeight = imgs[i].offsetTop
          if (imgHeight < windowHeight + bodyScrollHeight) {
             imgs[i].src = imgs[i].getAttribute('data-src')
             imgs[i].className = imgs[i].className.replace('lazy-load', '')
          }
        }
      }
    </script>
  </body>
</html>